<?

class Mojito_Session_SaveHandler_Cookies implements Zend_Session_SaveHandler_Interface
{

	private $Crypt;
	private $data;
	private $options;
	private $expiration;
	public function __construct(array $options)
	{
		$this->options=$options;
		$this->Crypt=new Zend_Filter_Encrypt_Mcrypt($options);
		$this->expiration = (!empty($this->options['expires'])?strtotime($this->options['expires']):0);
		if (!empty($_COOKIE[$this->options['cookie_iv']]))
		{
			$this->Crypt->setVector(base64_decode($_COOKIE[$this->options['cookie_iv']]));
		}
		else
		{
			setcookie($this->options['cookie_iv'], base64_encode($this->Crypt->getVector()), $this->expiration, $options['path'], $options['domain'], false, true);
		}
	}

	public function open($path, $name)
	{
		if (!empty($_COOKIE[$this->options['cookie_data']]))
		{
			$this->data=$this->Crypt->decrypt(base64_decode($_COOKIE[$this->options['cookie_data']]));
		}
		else $this->data='';
	}
	
	public function close()
	{
		return true;
	}
	
	public function read($id)
	{
		return $this->data;
	}
	
	public function write($id, $data)
	{
		$this->data=$data;
		setcookie($this->options['cookie_data'], base64_encode($this->Crypt->encrypt($this->data)), $this->expiration, $this->options['path'], $this->options['domain'], false, true);
		return true;
	}
	
	public function destroy($id)
	{
		return setcookie($this->options['cookie_data'], '', time()-60*60*24*30, $this->options['path'], $this->options['domain'], false, true);
	}
	
	public function gc($max)
	{
		return true;
	}
}